package eg;
import utils.JDBCUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/*
 *@Student 张策
 */
public class Text2 {
    public static void main(String[] args) {
        Connection conn=null;
        PreparedStatement pre1=null;
        PreparedStatement pre2=null;
        try {
            conn = JDBCUtils.getConnection();
            conn.setAutoCommit(false);
            String sql1="update acc set money=money+? where id=?;";
            String sql2="update acc set money=money-? where id=?;";
            pre1= conn.prepareStatement(sql1);
            pre2= conn.prepareStatement(sql2);
            pre1.setDouble(1,500);
            pre1.setInt(2,1);
            pre2.setDouble(1,500);
            pre2.setInt(2,2);
            pre1.executeUpdate();
            int i=1/0;
            pre2.executeUpdate();
            conn.commit();
        } catch (SQLException e) {
            if(conn!=null){
                try {
                    conn.rollback();
                }catch (SQLException e2){
                    e2.printStackTrace();
                }
            }
            e.printStackTrace();
        }finally {
            if (conn != null) {
                try {
                    conn.setAutoCommit(true); // 恢复自动提交模式
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            JDBCUtils.close(pre1,conn);
            JDBCUtils.close(pre2,null);
        }
    }
}